package mblog.core.persist.service.impl;

import mblog.core.data.GoodsKeyword;
import mblog.core.persist.dao.GoodsKeywordDao;
import mblog.core.persist.entity.GoodsKeywordPO;
import mblog.core.persist.entity.PostKeywordPO;
import mblog.core.persist.service.GoodsKeywordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class GoodsKeywordServiceImpl implements GoodsKeywordService {

    @Autowired
    private GoodsKeywordDao goodsKeywordDao;

    @Override
    public List<GoodsKeyword> keywords() {
        List<GoodsKeywordPO> keywordpos = goodsKeywordDao.hotKeywords();
        List<GoodsKeyword> goodsKeywords = new ArrayList<>();
        for (GoodsKeywordPO po : keywordpos) {
            goodsKeywords.add(new GoodsKeyword(po.getId(), po.getKeyword(), po.getAmount()));
        }
        return goodsKeywords;
    }

    @Override
    public void updateKeyword(String keyword) {
        GoodsKeywordPO goodsKeywordPO = goodsKeywordDao.findByKeyword(keyword);
        if (goodsKeywordPO != null) {
            goodsKeywordPO.addAmount(1);
            goodsKeywordDao.save(goodsKeywordPO);
            return;
        }
        goodsKeywordPO = new GoodsKeywordPO(keyword, 1L);
        goodsKeywordDao.save(goodsKeywordPO);
    }
}
